package net.cyndeline.GUI.actors

import akka.actor.Actor
import net.cyndeline.GUI.actors.messages.MapToParse
import javafx.animation.{Animation, TimelineBuilder, Timeline, KeyFrame}
import javafx.event.{ActionEvent, EventHandler}
import javafx.util.Duration
import net.cyndeline.scalarlib.entityComponent.miranda.Entity
import net.cyndeline.GUI.rendering.GraphicsParser

/**
 * Continuously checks the current game map for any entities that doesn't have a graphical representation stores
 * in the graphics container, and assigns them one.
 */
class RepresentationParser extends Actor {
  private val framesPerSecond = 60
  private val duration = Duration.millis(1000/framesPerSecond)
  private var currentRenderLoop: Option[Timeline] = None

  def receive = {
    case MapToParse(entityManager, graphics, map, tileWidth, tileHeight) => {
      val parser = new GraphicsParser(entityManager, graphics, tileWidth, tileHeight)

      /* A single frame that is looped. */
      val frame = new KeyFrame(duration,
        new EventHandler[ActionEvent]() {

          /* Everything that should happen in each frame. */
          def handle(event: ActionEvent) {
            var i = 0
            var j = 0

            while (i < map.width) {
              while (j < map.height) {
                val tile = map.tile(i, j)
                parser.createRepresentations(tile, i, j)
                j += 1
              }
              i += 1
            }

          } // Handle
        }) // Key frame

      /* Only runs one loop at the time. */
      if (currentRenderLoop.isDefined) {
        currentRenderLoop.get.stop()
      }

      currentRenderLoop = Option(TimelineBuilder.create()
        .cycleCount(Animation.INDEFINITE)
        .keyFrames(frame)
        .build())

      currentRenderLoop.get.play()

    } // Case
  }
}
